<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller\android\v13;


use app\api\model\Authority;

use app\api\model\Common;
use app\api\model\OrderModel;
use app\api\model\PurchaseUsage;
use app\api\model\RoutineUsage;
use think\Cache;
use think\Controller;

use think\Request;
use think\Exception;
use app\api\validate;
use  app\api\model\Approval;
use app\model\Common as ModelCommon;
use Think\Db;


class NewMaterial extends Controller
{
    protected $model;
    protected $us;
    
    //库存分类查询
    const  ClassificationQuery = '/bdinvcl/query';
    //报销凭证插入
    const  u8cReimbursement = '/voucher/insertU8c';
    //报销凭证插入批量
    const  u8cBath = '/voucher/insertU8cBatch';
    //存货详细信息
    const  u8cInvcDetail = '/common/invcDetail';
    //计量单位查询
    const  u8cquery = '/measdoc/query';
    //库存余额查询
    const  u8queryForStoreId = '/atp/queryForStoreId';
    
    //其他店铺可用数据量
    const  u8queryForOther = '/atp/queryForOther';
    //材料库存审核通过减少
    const  u8insertU8c = '/materialout/insertU8c';
    //材料价格查询
    const  u8cGetPrice = '/common/getPrice';
    
    //材料借调
    const  u8outAndIn = '/othersecondment/outAndIn';
    //打卡二维码
    const  qrcode = '/qrcode/chockIn';
    
    //库存材料出库u8c列表
    const  U8cForList = '/materialout/insertU8cForList';
    const  U8cIncode = '/common/detailOne';
    
    public function _initialize()
    {
        $this->model = new Authority();
        
        $this->us = Authority::check(1);
        
    }
    
    /**
     * 库存分类查询
     */
    public function InventoryClassificationQuery()
    {
        $request =  Request::instance()->get();
        if ($this->us['Inventory'] == 1 && isset($request['isUse']) && $request['isUse']==1) {
            r_date(null, 300, '库存盘点中，无法领用，请盘点完成后操作');
        }
        $data = ClassificationQueryMaterial(1,0,null,$this->us['user_id']);
        $data = json_decode($data, true);
        if ($data['status'] == 'success') {
            $list = $data['data'];
        } else {
            $list = null;
        }
        r_date($list, 200);
    }
    
    /**
     * 查询存货信息
     */
    public function U8cIncodeQuery()
    {
        $request = Authority::param(['invclasscode']);
        
        $data = U8cIncode($request['invclasscode'], $this->us['store_id']);
        $data = json_decode($data, true);
        
        if ($data['status'] == 'success') {
            $list = $data['data'];
        } else {
            $list = null;
        }
        r_date($list, 200);
    }
    
    /**
     * 库存分类查询
     */
    public function Company()
    {
        
        $data = Company();
        $data = json_decode($data, true);
        if ($data['status'] == 'success') {
            $list = json_decode($data['data']);
        } else {
            $list = null;
        }
        
        r_date($list, 200);
    }
    
    /**
     * 存货详细信息
     */
    public function u8cMaterialInvcDetail(Common $common)
    {
        $request = Authority::param(['invclasscode']);
        $data = Request::instance()->post();

        $m['store_id'] = $this->us['store_id'];
        if (isset($data['orderId']) && $data['orderId'] > 0) {
            $m = db('order')->where(['order_id' => $data['orderId']])->find();
        }
        $data = u8cInvcDetail($request['invclasscode'], $m['store_id'], 1, 200, null, 1, 0, null, $this->us['user_id'], 1);
        $data = json_decode($data, true);
        if ($data['status'] == 'success') {
            $list = $data['data'];
            $invclcodes = array_column($list, 'invclcode');
            $pendingCounts = $common->materialsPendingReview($m['store_id'], $invclcodes);
        
            foreach ($list as $k=>$item) {
                $list[$k]['price'] = '*';
                // 恢复 nabnum 计算（使用批量查询的结果）
                $invclcode = $item['invclcode'] ?? '';
                $list[$k]['nabnum'] = bcsub(
                    $item['nabnum'] ?? 0,
                    $pendingCounts[$invclcode] ?? 0,
                    2
                );
                 $list[$k]['nabnumsss'] = $pendingCounts[$invclcode]?? 0;
            }
        } else {
            $list = null;
        }

        r_date($list, 200);
    }
    
    /*
     * 材料领用是否超限
     */
    
    public function isOverrun()
    {
        $request      = Authority::param(['invclcode', 'orderId', 'square']);
        $capitalValue = db('capital_value')
            ->join('capital', 'capital_value.capital_id=capital.capital_id', 'left')
            ->join('detailed_option_value_material', 'detailed_option_value_material.option_value_id=capital_value.option_value_id', 'left')
            ->field('capital_value.capital_id,round(capital.square*recommended_quantity,2) as basicUpperLimit,if(exceeded_limit=0,0,round((recommended_quantity+recommended_quantity*exceeded_limit)*capital.square,2)) AS exceedingTheUpperLimit')
            ->where('capital.ordesr_id', $request['orderId'])
            ->where('capital.types', 1)
            ->where('capital.enable', 1)
            ->where('detailed_option_value_material.invcode', $request['invclcode'])
            ->group('capital_value.option_value_id,capital_value.capital_id')
            ->select();
        if (!empty($capitalValue)) {
            $material_usage       = db('material_usage')->where('order_id', $request['orderId'])->where('status', '<>', 2)->where('code', $request['invclcode'])->sum('square_quantity');
            $basicUpperLimitValue = array_column($capitalValue, 'basicUpperLimit');
            $basicUpperLimit      = array_sum($basicUpperLimitValue) - $material_usage;
            if (in_array(0, $basicUpperLimitValue)) {
                $basicUpperLimit = 0;
            }
            $exceedingTheUpperLimitValue = array_column($capitalValue, 'exceedingTheUpperLimit');
            $exceedingTheUpperLimit      = array_sum($exceedingTheUpperLimitValue) - $material_usage;
            if (in_array(0, $exceedingTheUpperLimitValue)) {
                $exceedingTheUpperLimit = 0;
            }
            
            if (($basicUpperLimit != 0 && $basicUpperLimit < $request['square'] && ($exceedingTheUpperLimit != 0 && $exceedingTheUpperLimit >= $request['square'])) || ($basicUpperLimit != 0 && $basicUpperLimit < $request['square'] && $exceedingTheUpperLimit == 0)) {
                r_date(null, 300, "当前领取数量大于平均值，确认领取？");
            }
            if ($exceedingTheUpperLimit != 0 && $exceedingTheUpperLimit < $request['square']) {
                r_date(null, 400, "当前领取数量大于最大限制无法领取，请调整领取数量或联系城市总处理。");
            }
        }
        
        r_date(null, 200);
    }
    
    /*
     * 材料库存增加
     */
    public function u8cMaterialCollectAdd(Approval $approval)
    {
        $data = Request::instance()->post();
        
        db()->startTrans();
        try {
            $user_id= $this->us['user_id'];
            $store_id= $this->us['store_id'];
            if(isset( $data['order_id']) &&  $data['order_id'] !=0){
                $user_id=db('order', config('database.zong'))->where('order_id',$data['order_id'])->value('assignor');
                $store_id=db('user', config('database.zong'))->where('user_id',$user_id)->value('store_id');
            }
            $id       = db('routine_usage')->insertGetId(['store_id' => $this->us['store_id'], 'stock_name' => '材料库存增加', 'user_id' =>$user_id, 'company' => '', 'status' => 0, 'voucher' => '', 'created_time' => time(), 'types' => 2, 'address' => $data['address'], 'phone' => $data['phone'], 'remake' => $data['remark'], 'name' => $data['name'], 'order_id' => $data['order_id']]);
            $jsonData = json_decode($data['jsonData'], true);
            foreach ($jsonData as $item) {
                db('routine_cart')->insertGetId(['id' => $id, 'invname' => $item['invname'], 'measname' => $item['measname'], 'invclcode' => $item['invclcode'], 'chooseNumber' => $item['chooseNumber'], 'created_time' => time(), 'store_id' => $store_id]);
            }
            $title = $this->us['username'] . '材料采购';
            db()->commit();
            $approval->Purchase($id, $title, $this->us['username'], 2);
            
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    /*
     * 材料记录type  1库存补充2新材料申请
     */
    public function MaterialRecords(RoutineUsage $routineUsage, PurchaseUsage $purchaseUsage)
    {
        $request = Authority::param(['type', 'startTime', 'endTime']);
        
        if ($request['type'] == 1) {
            $rows = $routineUsage;
            if ($request['startTime'] != '' && $request['startTime'] != 0 && $request['endTime'] != '' && $request['endTime'] != 0) {
                
                $start = strtotime(date('Y-m-d 00:00:00', strtotime($request['startTime'])));//获取指定月份的第一天
                $end   = strtotime(date('Y-m-d 23:59:59', strtotime($request['endTime']))); //获取指定月份的最后一天
                
                $rows->whereBetween('created_time', [$start, $end]);
            }
            $rows = $rows->where('types', 2)->where('secondment', 0)->where('user_id', $this->us['user_id'])->field('FROM_UNIXTIME(created_time,"%Y-%m-%d %H:%i") as created_time,id,status as statuss')->order('created_time desc')->select();
            
            
        } else {
            $rows = $purchaseUsage;
            if ($request['startTime'] != '' && $request['startTime'] != 0 && $request['endTime'] != '' && $request['endTime'] != 0) {
                $start = strtotime(date('Y-m-d 00:00:00', strtotime($request['startTime'])));//获取指定月份的第一天
                $end   = strtotime(date('Y-m-d 23:59:59', strtotime($request['endTime']))); //获取指定月份的最后一天
                $rows->whereBetween('created_time', [$start, $end]);
            }
            $rows = $rows->where('user_id', $this->us['user_id'])->field('stock_name,FROM_UNIXTIME(created_time,"%Y-%m-%d %H:%i") as created_time,id,status as statuss')->order('created_time desc')->select();
            
        }
        
        foreach ($rows as $k => $item) {
            if ($request['type'] == 1) {
                $data             = $routineUsage->routineCart()->where('id', $item['id'])->select();
                $rows[$k]['name'] = isset($data[0]['invname']) ? $data[0]['invname'] . '等' . count($data) . '类材料' : '';
                if ($item['statuss'] == 2) {
                    $rows[$k]['status'] = 3;
                } elseif ($item['statuss'] == 0) {
                    $rows[$k]['status'] = 4;
                } elseif ($item['statuss'] == 1) {
                    $status = array_column($data, 'status');
                    if (in_array(2, $status)) {
                        $rows[$k]['status'] = 1;
                    } else {
                        $rows[$k]['status'] = 2;
                    }
                }
                
            } else {
                $rows[$k]['name'] = $item['stock_name'] . '等类材料';
                if ($item['statuss'] == 2) {
                    $rows[$k]['status'] = 3;
                } elseif ($item['statuss'] == 0) {
                    $rows[$k]['status'] = 4;
                } elseif ($item['statuss'] == 1) {
                    $rows[$k]['status'] = 2;
                }
            }
            
            
            unset($rows[$k]['routineCart'], $rows[$k]['statuss']);
            
        }
        r_date($rows, 200);
    }
    
    /*
     * 1材料库存增加详情2新材料记录详情
     */
    public function MaterialRecordsInfo(RoutineUsage $routineUsage, PurchaseUsage $purchaseUsage)
    {
        $request = Authority::param(['id', 'type']);
        if ($request['type'] == 2) {
            $type            = 5;
            $request         = Authority::param(['id']);
            $rows            = $purchaseUsage;
            $data            = $rows->join('user', 'user.user_id=purchase_usage.user_id', 'left')->where('id', $request['id'])->field('stock_name,FROM_UNIXTIME(purchase_usage.created_time,"%Y-%m-%d %H:%i") as created_time,FROM_UNIXTIME(purchase_usage.adopt,"%Y-%m-%d %H:%i") as adopt,purchase_usage.id,purchase_usage.status as status,user.username,voucher,address,phone,remake,content,company,purchase_usage.number,purchase_usage.name,purchase_usage.address,purchase_usage.phone,purchase_usage.order_id')->find();
            $data['voucher'] = !empty($rows['voucher']) ? unserialize($rows['voucher']) : null;
            $rows            = [
                "stock_name" => $data['stock_name'],
                "created_time" => $data['created_time'],
                "id" => $data['id'],
                "status" => $data['status'],
                "username" => $data['username'],
                "voucher" => $data['voucher'],
                "order_id" => $data['order_id'],
                "address" => $data['address'],
                "phone" => $data['phone'],
                "remake" => $data['remake'],
                "content" => $data['content'],
                "name" => $data['name'],
                "routine_cart" => [[
                    "adopt" => $data['adopt'],
                    "id" => $data['id'],
                    "invname" => $data['stock_name'],
                    "measname" => $data['company'],
                    "invclcode" => 0,
                    "chooseNumber" => $data['number'],
                    "order_id" => $data['order_id'],
                    "status" => $data['status'],
                    "content" => $data['content'],
                    "purchase_car" => 0,
                    "original_number" => $data['number'],
                
                ]],
            ];
            
        } else {
            $type            = 4;
            $rows            = $routineUsage->with(['routineCart' => function ($query) {
                $query->withField('id');
            }]);
            $rows            = $rows->join('user', 'user.user_id=routine_usage.user_id', 'left')->where('id', $request['id'])->field('stock_name,FROM_UNIXTIME(routine_usage.created_time,"%Y-%m-%d %H:%i") as created_time,routine_usage.id,routine_usage.status as status,user.username,voucher,address,phone,remake,content,name,routine_usage.order_id')->find();
            $rows['voucher'] = !empty($rows['voucher']) ? unserialize($rows['voucher']) : null;
            foreach ($rows['routine_cart'] as $k => $item) {
                if (empty($item['original_number'])) {
                    $item['original_number'] = $item['chooseNumber'];
                }
                if ($item['original_number'] != $item['chooseNumber'] && $item['status'] == 2) {
                    if (!empty($item['content'])) {
                        $item['content'] = '入库数量有差异;' . $item['content'];
                    }
                    
                } elseif ($item['original_number'] != $item['chooseNumber']) {
                    $item['content'] = '入库数量有差异';
                }
//                if ($rows['status'] == 0) {
//                    $item['status'] = 0;
//                } elseif ($rows['status'] == 2) {
//                    $item['status'] = 2;
//                }
            }
            
            $rows['voucher'] = !empty($rows['voucher']) ? unserialize($rows['voucher']) : null;
            
        }
        $approval = db('approval', config('database.zong'))->join('bi_user', 'bi_user.user_id=approval.nxt_id', 'left')->where('approval.city_id', config('cityId'))->where('relation_id', $request['id'])->where('type', $type)->field('bi_user.username,FROM_UNIXTIME(approval.approved_time,"%Y-%m-%d %H:%i") as approved_time')->find();
        
        $rows['approvalUseraname'] = $approval['username'];
        $rows['approved_time']     = $approval['approved_time'];
        r_date($rows, 200);
    }
    
    /*
     * 材料用量标记
     */
    
    public function MaterialUsage()
    {
        $request                     = Authority::param(['cityId', 'storeId', 'title', 'startTime', 'endTime','invcode']);
        $detailed_use_material_usage = Db::connect(config('database.zong'))->table('detailed_use_material_usage')
            ->join('u8c_invbasdoc', 'u8c_invbasdoc.invcode=detailed_use_material_usage.invcode', 'left')
            ->join('store', 'detailed_use_material_usage.store_id=store.store_id', 'left');
        if ($request['storeId'] != 0) {
            $detailed_use_material_usage->where('store.store_id', $request['storeId']);
        }
        if ($request['title'] != "") {
            $detailed_use_material_usage->where('u8c_invbasdoc.invname', 'like', "%{$request['title']}%");
        }
        if ($request['invcode'] != "" && $request['invcode'] != 0) {
            $detailed_use_material_usage->where('u8c_invbasdoc.invcode', $request['invcode']);
        }
        if ($request['startTime'] != "" && $request['endTime'] != "") {
            $start = strtotime(date('Y-m-d 00:00:00', strtotime($request['startTime'])));//获取指定月份的第一天
            $end   = strtotime(date('Y-m-d 23:59:59', strtotime($request['endTime']))); //获取指定月份的最后一天
            $detailed_use_material_usage->whereBetween('detailed_use_material_usage.zero_hour_tim', [$start, $end]);
        }
        if ($request['cityId'] != 0) {
            $detailed_use_material_usage->where('store.city', $request['cityId']);
        }
        $list = $detailed_use_material_usage->whereRaw('(detailed_use_material_usage.recommended_quantity <> 0 and detailed_use_material_usage.self_num=0) or (detailed_use_material_usage.recommended_quantity = 0 and detailed_use_material_usage.self_num <> 0) or (detailed_use_material_usage.recommended_quantity <> 0 and detailed_use_material_usage.self_num <> 0)')->field('detailed_use_material_usage.invcode,round(sum(detailed_use_material_usage.self_num),2) as selfNum,round(sum(detailed_use_material_usage.avg),2) as avg,round(sum(detailed_use_material_usage.recommended_quantity),2) as recommendedQuantity,u8c_invbasdoc.measname as invname,u8c_invbasdoc.invname as materialName')->order('detailed_use_material_usage.self_num desc')->group('detailed_use_material_usage.invcode')->select();
        r_date($list, 200);
    }
    
    /*
 * 材料用量标记
 */
    
    public function MaterialUsageInfo(Common $common)
    {
        $request                        = Authority::param(['invcode', 'cityId', 'orderNo', 'startTime', 'endTime','page','limit','storeId']);
        if(empty($request['invcode'])){
            r_date(null, 300,"参数错误");
        }
        $page=empty($request['page'])?1:$request['page'];
        $limit=empty($request['limit'])?10:$request['limit'];
        $db                             = Common::city($request['cityId']);
        $detailed_option_value_material = Db::connect(config('database.' . $db['db']))->table('detailed_option_value_material')
            ->field('detailed_option_value_material.invcode,detailed_option_value_material.recommended_quantity,detailed_option_value_material.option_value_id')
            ->group('detailed_option_value_material.option_value_id,detailed_option_value_material.invcode')
            ->buildSql();
        
        $capital_value               = Db::connect(config('database.' . $db['db']))->table('capital_value')
            ->join('capital', 'capital_value.capital_id=capital.capital_id', 'left')
            ->join('detailed', 'detailed.detailed_id=capital.projectId', 'left')
            ->join([$detailed_option_value_material => 'detailed_option_value_material'], 'detailed_option_value_material.option_value_id=capital_value.option_value_id', 'left')
            ->field("capital.ordesr_id,
      CONCAT('[', GROUP_CONCAT(DISTINCT JSON_OBJECT('capitalId',CAST(capital.capital_id AS CHAR),'title', capital.class_b,'square',capital.square,'projectId',`capital`.`projectId`) SEPARATOR ','), ']') as  capitalContent,
	`detailed_option_value_material`.*,GROUP_CONCAT(capital.capital_id,'_',`detailed_option_value_material`.`recommended_quantity`) as recommendedQuantity")
            ->where(['capital.types' => 1, 'capital.enable' => 1, 'capital.agency' => 0])
            ->whereIn('capital.fen', [1, 4])
            ->where('detailed_option_value_material.invcode', $request['invcode'])
            ->group('capital.ordesr_id')
            ->buildSql();
        $detailed_use_material_usage = Db::connect(config('database.' . $db['db']))->table('order')
            ->join('material_usage', 'material_usage.order_id=order.order_id', 'left')
            ->join('user', 'user.user_id=order.assignor', 'left')
            ->join([$capital_value => 'capital'], 'capital.ordesr_id=material_usage.order_id', 'right');
        if ($request['orderNo'] != 0) {
            $detailed_use_material_usage->where('order.order_no', $request['orderNo']);
        }
        if ($request['storeId'] != 0) {
            $detailed_use_material_usage->where('user.store_id', $request['storeId']);
        }
        if ($request['startTime'] != "" && $request['endTime'] != "") {
            $start = strtotime(date('Y-m-d 00:00:00', strtotime($request['startTime'])));//获取指定月份的第一天
            $end   = strtotime(date('Y-m-d 23:59:59', strtotime($request['endTime']))); //获取指定月份的最后一天
            $detailed_use_material_usage->whereBetween('material_usage.adopt', [$start, $end]);
        }
        
        $list = $detailed_use_material_usage->where('material_usage.code', $request['invcode'])->where('material_usage.status', 1)
            ->field("order.order_no as orderNo,capital.*,
        CONCAT('[', GROUP_CONCAT(JSON_OBJECT('name', material_usage.square_quantity,'company',material_usage.company,'adopt',FROM_UNIXTIME(material_usage.adopt,'%Y-%m-%d %H:%i')) SEPARATOR ','), ']') as  content")
            ->group('material_usage.order_id')
            ->order('material_usage.order_id desc')
            ->page($page,$limit)
            ->select();
        foreach ($list as $k => $item) {
            $list[$k]['orderId'] = $item['ordesr_id'];
            $recommendedQuantity = '';
            if(!empty($item['recommendedQuantity'])){
                $recommendedQuantity = explode(",", $item['recommendedQuantity']);
            }
            $capitalContent      = json_decode($item['capitalContent'], true);
            $name                = json_decode($item['content'], true);
            $list[$k]['assembleCount'] = 0;
            foreach ($capitalContent as $key => $value) {
                $count = [];
                if ($recommendedQuantity) {
                    foreach ($recommendedQuantity as $val) {
                        if (strstr($val, (string)$value['capitalId']) !== false) {
                            $count[] = explode("_", $val)[1];
                        }
                    }
                }
                $capitalContent[$key]['count'] = array_sum($count);
                $list[$k]['assembleCount'] += $capitalContent[$key]['count']*$capitalContent[$key]['square'];
               
                
            }
            $list[$k]['generalUse']     = array_sum(array_column($name, 'name'));
            $list[$k]['content']     = $name;
            $list[$k]['capitalContent'] = $capitalContent;
            unset($list[$k]['option_value_id1'], $list[$k]['ordesr_id'],$list[$k]['recommendedQuantity'], $list[$k]['recommended_quantity'],  $list[$k]['option_value_id'], $list[$k]['invcode']);
            
        }
        r_date($list, 200);
    }
    
}